<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" style="width: 200px;" @keyup.enter="handleQuery">
          <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="积分状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择积分状态" clearable style="width: 200px;">
          <el-option label="已过期" value="1" />
          <el-option label="可使用" value="0" />
          <el-option label="已使用" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="times">
        <el-date-picker clearable v-model="queryParams.times" type="date" value-format="YYYY-MM-DD" placeholder="请选择时间" style="width:200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="积分数量" prop="isvalue">
        <el-input v-model="queryParams.isvalue" placeholder="请输入积分数量" clearable @keyup.enter="handleQuery" style="width:200px;"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['chy:integraldetails:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['chy:integraldetails:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['chy:integraldetails:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['chy:integraldetails:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="integraldetailsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="明细编号" align="center" prop="id" />
      <el-table-column label="用户姓名" align="center">
        <template #default="scope">
          {{ getUserNameById(scope.row.userId) }}
        </template>
      </el-table-column>
      <el-table-column label="积分状态" align="center" prop="status">
        <template #default="scope">
          <!-- 根据不同状态显示不同文字和 tag 类型 -->
          <el-tag :type="scope.row.status == '0' ? 'success' : scope.row.status == '1' ? 'danger' : 'warning'">
            {{ scope.row.status == '0' ? '可使用' : scope.row.status == '1' ? '已过期' : '已使用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center" prop="times" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.times, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="积分内容" align="center">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="showRichTextDialog('content', scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="积分数量" align="center" prop="isvalue" />
      <el-table-column label="备注信息" align="center">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="showRichTextDialog('remark', scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['chy:integraldetails:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['chy:integraldetails:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 富文本详情对话框 -->
    <el-dialog v-model="richTextDialogVisible" title="详情" width="80%">
      <div v-html="richTextContent"></div>
    </el-dialog>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改积分明细对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="integraldetailsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户姓名" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户">
            <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="积分状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择积分状态">
            <el-option label="已过期" value="1" />
            <el-option label="可使用" value="0" />
            <el-option label="已使用" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="times">
          <el-date-picker clearable v-model="form.times" type="date" value-format="YYYY-MM-DD" placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="积分内容">
          <editor v-model="form.content" :min-height="192" :config="editorConfig"/>
        </el-form-item>
        <el-form-item label="积分数量" prop="isvalue">
          <el-input v-model="form.isvalue" placeholder="请输入积分数量" />
        </el-form-item>
        <el-form-item label="备注信息">
          <editor v-model="form.remark" :min-height="192" :config="editorConfig"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Integraldetails">
import { listIntegraldetails, getIntegraldetails, delIntegraldetails, addIntegraldetails, updateIntegraldetails } from "@/api/chy/integraldetails"
import { listUsers } from "@/api/gas/users"

const { proxy } = getCurrentInstance()

const integraldetailsList = ref([])
const usersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    status: null,
    times: null,
    isvalue: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
const richTextDialogVisible = ref(false)
const richTextContent = ref('')

/**
 * 显示富文本详情对话框
 * @param {string} type - 内容类型，'content' 或 'remark'
 * @param {object} row - 当前行数据
 */
function showRichTextDialog(type, row) {
  richTextContent.value = row[type]
  richTextDialogVisible.value = true
}
/** 查询积分明细列表 */
function getList() {
  loading.value = true
  listIntegraldetails(queryParams.value).then(response => {
    integraldetailsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getListUsers() {
  loading.value = true
  queryParams.value.params = {}
  listUsers(queryParams.value).then(response => {
    usersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getUserNameById(userId) {
  const user = usersList.value.find(user => user.id == userId)
  return user ? user.userName : '未知用户'
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    status: null,
    times: null,
    content: null,
    isvalue: null,
    remark: null
  }
  proxy.resetForm("integraldetailsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加积分明细"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getIntegraldetails(_id).then(response => {
    // 确保 status 为字符串类型，与下拉框选项的 value 类型一致
    const data = response.data
    data.status = String(data.status)
    form.value = data
    open.value = true
    title.value = "修改积分明细"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["integraldetailsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateIntegraldetails(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addIntegraldetails(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除积分明细编号为"' + _ids + '"的数据项？').then(function () {
    return delIntegraldetails(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('chy/integraldetails/export', {
    ...queryParams.value
  }, `integraldetails_${new Date().getTime()}.xlsx`)
}

getList()
getListUsers()
</script>
